package com.rabincorp.tactile.util;



import java.io.Serializable;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.log4j.Logger;

/**
 * @author aphilipp
 */
public final class CacheService {

    private static final Logger logger = Logger.getLogger(CacheService.class);
    
    private static CacheService instance = null;
    private CacheManager manager;

    public static CacheService getDefault() {
	if (instance == null) {
	    synchronized (CacheService.class) {
		instance = new CacheService();
	    }
	}
	return instance;
    }

    private CacheService() {
	initCache();
    }

    private void initCache() {
	logger.info("Initialize Cache Service.");
	this.manager = CacheManager.getInstance();
    }

    public Object getCachedObject(String region, String key) {
	Object obj = null;

	Cache cache = manager.getCache(region);
	Element element = null;
	if (cache != null) {
	    element = cache.get(key);
	    if (element!=null) {
		obj =  element.getObjectValue();
	    }
	}

	return obj;
    }

    public void putCachedObject(Object obj, String region, String key) {
	Element element = new Element(key, obj);

	Cache cache = manager.getCache(region);
	if (cache!=null) {
	    cache.put(element);	    
	}
    }

    public void shutdown() {
	logger.info("Shutting down Cache Service.");
	if (manager != null) {
	    manager.shutdown();
	}
    }
}
